package sixyz.dao;

import sixyz.util.JDBCUtils;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

// 泛型类
public class BaseDAO<T> {

    public BaseDAO() {

    }

    public void save(T t) throws IllegalAccessException, SQLException, ClassNotFoundException {
        String sql = "insert into";
        String columnName = "";
        String columnParameter = "";
        String begin = "(";
        String end = ")";
        // 获取类的引用（类对象）
        Class classReference = t.getClass();
        // 得到类的简写名称，并转化成小写
        String tableName = classReference.getSimpleName().toLowerCase();
        // sql语句表名部分
        sql = sql + " " + tableName;
        // 存储 t 中 的属性
        List fieldValues = new ArrayList<>();
        // 获得所有类属性，包括private
        Field[] fieldArray = classReference.getDeclaredFields();
        for (Field eachField : fieldArray) {
            // 访问允许
            eachField.setAccessible(true);
            // 获取每个字段的名字
            String eachFieldName = eachField.getName();
            // 返回对象t的 对应的 属性值
            Object eachValue = eachField.get(t);
            columnName = columnName + "," + eachFieldName;
            columnParameter = columnParameter + ", ?";
            fieldValues.add(eachValue);
        }
        // 合成并打印sql语句
        // 截取第一个码元之后的内容
        columnName = columnName.substring(1);
        columnParameter = columnParameter.substring(1);
        sql = sql + begin + columnName + end;
        sql = sql + " values" + begin + columnParameter + end;
        // 执行更新操作
        JDBCUtils jdbcUtils = new JDBCUtils();
        Connection connection = jdbcUtils.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < fieldValues.size(); i++) {
            preparedStatement.setObject(i + 1, fieldValues.get(i));
        }
        preparedStatement.executeUpdate();
        preparedStatement.close();
        connection.close();
    }


}
